package controller

import (
	"GoTime/models"
	"encoding/json"
	"log"
	"net/http"
	"strconv"
	"strings"
	"time"

	. "GoTime/utils"

	"github.com/beego/beego/validation"
	"github.com/gin-gonic/gin"
	"github.com/spf13/cast"
	"xorm.io/builder"
	"xorm.io/xorm"
)

var DrivingCarTypeMap map[string]int64 = map[string]int64{
	"A1": 1,
	"A2": 2,
	"A3": 3,
	"B1": 4,
	"B2": 5,
	"C1": 6,
	"C2": 7,
	"C3": 8,
	"C4": 9,
	"C5": 10,
	"D":  11,
	"E":  12,
	"F":  13,
	"M":  14,
	"N":  15,
	"P":  16,
}

func GetCoachList(c *gin.Context) {
	// 从请求参数中获取school_id值
	schoolId := c.Query("school_id")

	// 创建一个Validation对象用于数据验证
	valid := validation.Validation{}

	// 验证school_id字段是否为空，并设置自定义错误信息
	valid.Required(schoolId, "school_id").Message("请输入id")

	// 检查是否有验证错误
	if valid.HasErrors() {
		// 遍历所有的验证错误
		for _, err := range valid.Errors {
			// 返回JSON格式的错误信息
			c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err.Message})
			return // 结束函数执行
		}
	}

	// 从请求参数中获取page值，默认为1
	page := cast.ToInt(c.DefaultQuery("page", "1"))

	// 从请求参数中获取pageSize值，默认为15
	pageSize := cast.ToInt(c.DefaultQuery("pageSize", "15"))

	// 计算偏移量
	offset := (page - 1) * pageSize

	// 创建一个builder.Cond对象用于构建查询条件
	filter := builder.NewCond()

	// 如果请求参数中包含name字段且不为空，添加name字段的模糊查询条件
	if username := c.Query("name"); username != "" {
		filter = filter.And(builder.Like{"u.name", username})
	}

	// 如果请求参数中包含phone字段且不为空，添加phone字段的模糊查询条件
	if phone := c.Query("phone"); phone != "" {
		filter = filter.And(builder.Like{"u.phone", phone})
	}

	// 如果请求参数中包含id_number字段且不为空，添加id_number字段的模糊查询条件
	if idNumber := c.Query("id_number"); idNumber != "" {
		filter = filter.And(builder.Like{"u.id_number", idNumber})
	}

	// 如果请求参数中包含teaching_car_type字段且不为空，添加teaching_car_type字段的精确查询条件
	if trainingCarType := c.Query("teaching_car_type"); trainingCarType != "" {
		filter = filter.And(builder.Eq{"c.teaching_car_type": trainingCarType})
	}

	// 如果请求参数中包含status字段且不为空，添加status字段的精确查询条件
	if status := c.Query("status"); status != "" {
		filter = filter.And(builder.Eq{"c.status": status})
	}

	// 如果请求参数中包含login_status字段且不为空，添加login_status字段的精确查询条件
	if loginStatus := c.Query("login_status"); loginStatus != "" {
		filter = filter.And(builder.Eq{"c.login_status": loginStatus})
	}

	// 如果请求参数中包含type字段且不为空，根据type字段的值添加subject字段的精确查询条件
	if cType := c.Query("type"); cType != "" {
		var subject []string
		if cType == "1" {
			subject = []string{"1", "4"}
		} else if cType == "2" {
			subject = []string{"2"}
		} else if cType == "3" {
			subject = []string{"3"}
		}
		// 如果type字段不在指定范围内，可以考虑设置默认值或返回错误信息
		filter = filter.And(builder.In("c.subject", subject))
	}

	// 调用models层的GetCoachList方法，获取教练列表数据
	count, list, err := new(models.Coach).GetCoachList(filter, cast.ToInt(schoolId), pageSize, offset)

	// 检查是否有错误
	if err != nil {
		// 如果获取教练列表时发生错误，返回状态码201和错误信息
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err.Error()})
		return // 出现错误，直接返回
	}

	// 返回JSON格式的响应数据
	c.JSON(http.StatusOK, gin.H{"code": 200, "msg": "success", "data": gin.H{"list": list, "count": count}})
	return
}

func AddCoach(c *gin.Context) {
	var err error
	coach := new(models.Coach)
	user := new(models.User)
	portrait := new(models.Portrait)
	cert := new(models.CoachCert)
	// 从请求参数中获取数据
	if err := c.ShouldBind(coach); err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err.Error()})
		return
	}
	log.Println(coach)
	if err := c.ShouldBind(user); err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err.Error()})
		return
	}
	if err := c.ShouldBind(portrait); err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err.Error()})
		return
	}
	// 验证数据
	valid := validation.Validation{}
	valid.Required(user.Name, "name").Message("请输入教练姓名")
	valid.Required(user.Phone, "phone").Message("请输入手机号")
	valid.Required(user.IdNumber, "id_number").Message("请输入身份证号")
	//valid.Required(coach.Subject, "subject").Message("请上传头像")
	if valid.HasErrors() {
		for _, err := range valid.Errors {
			c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err.Message})
			return
		}
	}

	if c.PostForm("licence_grant_date") == "" {
		coach.LicenceGrantDate = time.Now()
	} else {
		if coach.LicenceGrantDate, err = time.Parse("2006-01-02", c.PostForm("licence_grant_date")); err != nil {
			c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "驾驶证初领日期格式错误"})
			return
		}
	}
	if c.PostForm("entry_date") == "" {
		coach.EntryDate = time.Now()
	} else {
		if coach.EntryDate, err = time.Parse("2006-01-02", c.PostForm("entry_date")); err != nil {
			c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "入职日期格式错误"})
			return
		}
	}
	ok, school, err := new(models.School).GetSchoolById(cast.ToInt(c.PostForm("school_id")))
	if err != nil || !ok {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "驾校不存在"})
		return
	}
	// 验证通过，执行业务逻辑代码
	var engine *xorm.Engine        // 声明一个指向xorm引擎的指针
	engine = models.Engine         // 将models包中的Engine赋值给engine变量
	session := engine.NewSession() // 创建一个新的数据库会话
	defer session.Close()          // 确保在函数结束时关闭会话，释放资源
	// 保存教练信息
	if err := session.Begin(); err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err.Error()})
		return
	}
	//检测是否存在该手机号
	if ok, _ := session.Table("dts_user").Where("phone = ? and type = '3' and isused = '1'", user.Phone).Get(new(models.User)); ok {
		session.Rollback()
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": user.Phone + " - 手机号已存在"})
		return
	}
	user.IdType = "1"                                         // 设置用户证件类型为身份证
	user.Type = "3"                                           // 设置用户类型为教练
	user.Password = Md5(user.IdNumber[len(user.IdNumber)-6:]) // 对密码进行加密
	user.Isused = "1"                                         // 设置用户状态为正在使用
	if _, err := session.Insert(user); err != nil {
		session.Rollback()
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err.Error()})
		return
	}
	portrait.UserId = user.Id
	portrait.AddTime = time.Now()
	if _, err := session.Insert(portrait); err != nil {
		session.Rollback()
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err.Error()})
		return
	}
	if coach.DrivingCarType != "" && coach.TeachingCarType != "" {
		if DrivingCarTypeMap[coach.DrivingCarType] <= DrivingCarTypeMap[coach.TeachingCarType] {

		} else {
			session.Rollback()
			c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "准驾车型与准教车型不匹配"})
			return
		}
	}
	coach.SchoolId = cast.ToInt(c.PostForm("school_id"))
	coach.UserId = user.Id
	coach.PortraitId = portrait.Id
	coach.AddTime = time.Now()
	coach.Isused = "1"
	//请求百度人脸识别接口
	log.Println("百度人脸识别接口：", user.Phone, user.IdNumber)
	if err = BaiduCheck(portrait.ImageUrl, user.Phone, user.IdNumber, school.Province); err != nil {
		session.Rollback()
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err.Error()})
		return
	}
	// 判断是否存档，存档的只记录备案状态，否则进行备案
	if c.PostForm("retain") == "1" {
		if _, err := session.Insert(coach); err != nil {
			session.Rollback()
		}
		c.JSON(http.StatusOK, gin.H{"code": 200, "msg": "教练添加成功"})
		return
	} else {
		// 进行备案
		// 向全国平台获取统一编号
		coach.InstitutionCode = GetInstitutionCode(strings.TrimRight(user.IdNumber, "c"))
		log.Println(coach.InstitutionCode)
		// 调用接口，进行备案
		// 保存教练信息
		if _, err := session.Insert(coach); err != nil {
			session.Rollback()
			c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err.Error()})
			return
		}
		// 获取机构编码
		if school.City == "371100" || school.Province == "420000" {
			if err = c.ShouldBind(cert); err != nil {
				c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err.Error()})
				return
			}
			cert.CoachId = coach.Id
			cert.AddTime = time.Now()
			_, err = session.Insert(cert)
			if err != nil {
				session.Rollback()
				c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err.Error()})
				return
			}
		}
		if c.PostForm("province") == "420000" || c.PostForm("province") == "450000" {
			// 上传证件
			if msg, err := CertImageUp(c.PostForm("id_card"), 20, coach.InstitutionCode, c.PostForm("province"), c.PostForm("city")); err != nil {
				c.JSON(http.StatusOK, gin.H{"code": 201, "msg": msg})
				return
			}
			if msg, err := CertImageUp(c.PostForm("id_card_b"), 26, coach.InstitutionCode, c.PostForm("province"), c.PostForm("city")); err != nil {
				c.JSON(http.StatusOK, gin.H{"code": 201, "msg": msg})
				return
			}
			if msg, err := CertImageUp(c.PostForm("dir_lic"), 10, coach.InstitutionCode, c.PostForm("province"), c.PostForm("city")); err != nil {
				c.JSON(http.StatusOK, gin.H{"code": 201, "msg": msg})
				return
			}
			if msg, err := CertImageUp(c.PostForm("dir_lic_b"), 27, coach.InstitutionCode, c.PostForm("province"), c.PostForm("city")); err != nil {
				c.JSON(http.StatusOK, gin.H{"code": 201, "msg": msg})
				return
			}
			if msg, err := CertImageUp(c.PostForm("acc"), 28, coach.InstitutionCode, c.PostForm("province"), c.PostForm("city")); err != nil {
				c.JSON(http.StatusOK, gin.H{"code": 201, "msg": msg})
				return
			}
		}
		//备案1
		if err = coach.RecordCoach(school.InstitutionCode, user, school.Province, school.City, portrait.InstitutionCode, "", portrait.ImageUrl); err != nil {
			session.Rollback()
			c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err.Error()})
			return
		}
		//更新
		_, err = session.Exec("update dts_coach set record_status=?  where id = ?", "1", coach.Id)
		if err != nil {
			session.Rollback()
			return
		}
	}
	if err := session.Commit(); err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err.Error()})
		return
	}
	// 业务逻辑代码执行完毕，返回成功响应
	// 最后一步，上传快鸭
	c.JSON(http.StatusOK, gin.H{"code": 200, "msg": "教练备案成功"})
}

func EditCoach(c *gin.Context) {
	coach := new(models.Coach)       // 定义一个Coach结构体变量用于存储教练信息
	user := new(models.User)         // 定义一个User结构体变量用于存储用户信息
	portrait := new(models.Portrait) // 定义一个Portrait结构体变量用于存储头像信息
	cert := new(models.CoachCert)    // 定义一个CoachCert结构体变量用于存储教练证件信息

	// 验证数据
	valid := validation.Validation{}
	valid.Required(c.PostForm("coach_id"), "coach_id").Message("请输入教练id")
	if valid.HasErrors() {
		for _, err := range valid.Errors {
			c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err.Message})
			return
		}
	}

	// 通过教练ID获取教练信息
	coach, err := new(models.Coach).GetCoachById(c.PostForm("coach_id"))
	if err != nil || coach.Id <= 0 {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "教练不存在"})
		return
	}

	user, err = new(models.User).GetUserById(coach.UserId)
	if err != nil || user.Id <= 0 {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "用户不存在"})
		return
	}
	// 从请求参数中获取数据并绑定到coach结构体
	if err := c.ShouldBind(coach); err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err.Error()})
		return
	}
	log.Println(coach)

	// 从请求参数中获取数据并绑定到user结构体
	if err := c.ShouldBind(user); err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err.Error()})
		return
	}

	// 从请求参数中获取数据并绑定到portrait结构体
	if err := c.ShouldBind(portrait); err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err.Error()})
		return
	}

	// 查询指定驾校ID的驾校信息
	ok, school, err := new(models.School).GetSchoolById(cast.ToInt(c.PostForm("school_id")))
	if err != nil || !ok {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "驾校不存在"})
		return
	}

	// 验证通过，执行业务逻辑代码
	var engine *xorm.Engine        // 声明一个指向xorm引擎的指针
	engine = models.Engine         // 将models包中的Engine赋值给engine变量
	session := engine.NewSession() // 创建一个新的数据库会话
	defer session.Close()          // 确保在函数结束时关闭会话，释放资源

	// 开始一个数据库事务
	if err := session.Begin(); err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err.Error()})
		return
	}

	// 检查准驾车型与准教车型是否匹配
	if coach.DrivingCarType != "" && coach.TeachingCarType != "" {
		if DrivingCarTypeMap[coach.DrivingCarType] <= DrivingCarTypeMap[coach.TeachingCarType] {
		} else {
			session.Rollback()
			c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "准驾车型与准教车型不匹配"})
			return
		}
	}

	// 根据省份和城市处理教练证件信息
	if c.PostForm("city") == "371100" || c.PostForm("province") == "420000" {
		if err = c.ShouldBind(cert); err != nil {
			c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err.Error()})
			return
		}
		ok, _, err := new(models.CoachCert).GetByCoachId(coach.Id)
		if err != nil {
			c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err.Error()})
			return
		} else if ok {
			if !cert.Edit(coach.Id, "acc", "id_card", "dir_lic", "id_card_b", "dir_lic_b") {
				c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "证件信息不完整"})
				return
			}
		} else {
			if err = c.ShouldBind(cert); err != nil {
				c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err.Error()})
				return
			}
			cert.CoachId = coach.Id
			cert.AddTime = time.Now()
			_, err = session.Insert(cert)
			if err != nil {
				session.Rollback()
				c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err.Error()})
				return
			}
		}
	}

	// 设置教练记录状态为0（删除状态）
	coach.RecordStatus = "0"

	// 处理头像信息
	if c.PostForm("portrait_code") != "" {
		if coach.PortraitId > 0 {
			// 更新头像信息
			_, *portrait, _ = new(models.Portrait).GetStudentPortraitById(int64(coach.PortraitId))
			portrait.ImageUrl = c.PostForm("image_url")
			portrait.UserId = coach.UserId
			portrait.InstitutionCode = c.PostForm("portrait_code")
			if portrait, err = portrait.Edit("image_url", "portrait_code", "user_id"); err != nil {
				session.Rollback()
				c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err.Error()})
				return
			}
		} else {
			// 插入新的头像信息
			portrait.UserId = coach.UserId
			portrait.AddTime = time.Now()
			portrait.TerminalId = 0
			_, err = session.Insert(portrait)
			if err != nil {
				session.Rollback()
				c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err.Error()})
				return
			}
			coach.PortraitId = portrait.Id
		}
	} else if coach.PortraitId != 0 {
		// 更新头像的用户ID
		portrait.UserId = coach.UserId
		if portrait, err = portrait.Edit("user_id"); err != nil {
			session.Rollback()
			c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err.Error()})
			return
		}
	} else {
		session.Rollback()
		c.JSON(http.StatusOK, gin.H{"code": 0, "msg": "头像不能为空"})
		return
	}

	// 处理教练证发证日期
	if c.PostForm("licence_grant_date") == "" {
		coach.LicenceGrantDate = time.Now()
	} else {
		if coach.LicenceGrantDate, err = time.Parse("2006-01-02", c.PostForm("licence_grant_date")); err != nil {
			c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err.Error()})
			return
		}
	}

	// 处理教练入职日期
	if c.PostForm("entry_date") == "" {
		coach.EntryDate = time.Now()
	} else {
		if coach.EntryDate, err = time.Parse("2006-01-02", c.PostForm("entry_date")); err != nil {
			c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err.Error()})
			return
		}
	}

	// 设置教练的准教车型和准驾车型
	if coach.TeachingCarTypes == "" {
		coach.TeachingCarTypes = coach.TeachingCarType
	}
	if coach.DrivingCarTypes == "" {
		coach.DrivingCarTypes = coach.DrivingCarType
	}
	// 更新用户信息
	//user.Phone = user.Phone
	log.Println(user.IdNumber, user.IdType, "1111111111111111111111111111111")
	if _, err = session.Table("dts_user").Cols("name", "sex", "nation", "phone", "address", "id_type", "id_number").Where("id = ?", user.Id).Update(user); err != nil {
		session.Rollback()
		c.JSON(http.StatusOK, gin.H{"code": 0, "msg": "教练员修改失败"})
		return
	}
	// 设置教练的机构编号
	if coach.InstitutionCode == "" {
		if c.PostForm("portrait_code") != "" {
			coach.InstitutionCode = GetInstitutionCode(strings.TrimRight(user.IdNumber, "c"))
			log.Println(coach.InstitutionCode)
			if school.Province == "420000" || school.Province == "450000" {
				// 上传证件
				if msg, err := CertImageUp(c.PostForm("id_card"), 20, coach.InstitutionCode, c.PostForm("province"), c.PostForm("city")); err != nil {
					c.JSON(http.StatusOK, gin.H{"code": 201, "msg": msg})
					return
				}
				if msg, err := CertImageUp(c.PostForm("id_card_b"), 26, coach.InstitutionCode, c.PostForm("province"), c.PostForm("city")); err != nil {
					c.JSON(http.StatusOK, gin.H{"code": 201, "msg": msg})
					return
				}
				if msg, err := CertImageUp(c.PostForm("dir_lic"), 10, coach.InstitutionCode, c.PostForm("province"), c.PostForm("city")); err != nil {
					c.JSON(http.StatusOK, gin.H{"code": 201, "msg": msg})
					return
				}
				if msg, err := CertImageUp(c.PostForm("dir_lic_b"), 27, coach.InstitutionCode, c.PostForm("province"), c.PostForm("city")); err != nil {
					c.JSON(http.StatusOK, gin.H{"code": 201, "msg": msg})
					return
				}
				if msg, err := CertImageUp(c.PostForm("acc"), 28, coach.InstitutionCode, c.PostForm("province"), c.PostForm("city")); err != nil {
					c.JSON(http.StatusOK, gin.H{"code": 201, "msg": msg})
					return
				}
			}

			// 更新教练信息
			if coach.Status == "1" {
				coach.LoginStatus = "0"
				if _, err = session.Cols("institution_code", "finger_id", "portrait_id", "licence_number", "licence_grant_date", "occupation_number", "occupation_rank", "driving_car_type", "teaching_car_type", "entry_date", "status", "record_status", "login_status", "subject", "departure_date").Where("id = ?", coach.Id).Update(coach); err != nil {
					session.Rollback()
					c.JSON(http.StatusOK, gin.H{"code": 0, "msg": "教练员修改失败"})
					return
				}
			} else {
				if _, err = session.Cols("institution_code", "finger_id", "portrait_id", "licence_number", "licence_grant_date", "occupation_number", "occupation_rank", "driving_car_type", "teaching_car_type", "entry_date", "status", "record_status", "subject").Where("id = ?", coach.Id).Update(coach); err != nil {
					session.Rollback()
					c.JSON(http.StatusOK, gin.H{"code": 0, "msg": "教练员修改失败"})
					return
				}
			}
		} else {
			session.Rollback()
			c.JSON(http.StatusOK, gin.H{"code": 0, "msg": "头像不能为空"})
			return
		}
	} else {
		// 根据省份处理教练证件信息
		if c.PostForm("province") == "420000" || c.PostForm("province") == "450000" {
			// 上传证件
			if msg, err := CertImageUp(c.PostForm("id_card"), 20, coach.InstitutionCode, c.PostForm("province"), c.PostForm("city")); err != nil {
				c.JSON(http.StatusOK, gin.H{"code": 201, "msg": msg})
				return
			}
			if msg, err := CertImageUp(c.PostForm("id_card_b"), 26, coach.InstitutionCode, c.PostForm("province"), c.PostForm("city")); err != nil {
				c.JSON(http.StatusOK, gin.H{"code": 201, "msg": msg})
				return
			}
			if msg, err := CertImageUp(c.PostForm("dir_lic"), 10, coach.InstitutionCode, c.PostForm("province"), c.PostForm("city")); err != nil {
				c.JSON(http.StatusOK, gin.H{"code": 201, "msg": msg})
				return
			}
			if msg, err := CertImageUp(c.PostForm("dir_lic_b"), 27, coach.InstitutionCode, c.PostForm("province"), c.PostForm("city")); err != nil {
				c.JSON(http.StatusOK, gin.H{"code": 201, "msg": msg})
				return
			}
			if msg, err := CertImageUp(c.PostForm("acc"), 28, coach.InstitutionCode, c.PostForm("province"), c.PostForm("city")); err != nil {
				c.JSON(http.StatusOK, gin.H{"code": 201, "msg": msg})
				return
			}
		}

		// 更新教练信息
		if coach.Status == "1" {
			coach.LoginStatus = "0"
			if _, err = session.Cols("finger_id", "portrait_id", "licence_number", "licence_grant_date", "occupation_number", "occupation_rank", "driving_car_type", "teaching_car_type", "entry_date", "status", "record_status", "login_status", "subject", "departure_date").Where("id = ?", coach.Id).Update(coach); err != nil {
				session.Rollback()
				c.JSON(http.StatusOK, gin.H{"code": 0, "msg": "教练员修改失败"})
				return
			}
		} else {
			if _, err = session.Cols("finger_id", "portrait_id", "licence_number", "licence_grant_date", "occupation_number", "occupation_rank", "driving_car_type", "teaching_car_type", "entry_date", "status", "record_status", "subject").Where("id = ?", coach.Id).Update(coach); err != nil {
				session.Rollback()
				c.JSON(http.StatusOK, gin.H{"code": 0, "msg": "教练员修改失败"})
				return
			}
		}
	}

	// 人脸识别
	log.Println("百度人脸识别接口：", user.Phone, user.IdNumber)
	if err = BaiduCheck(portrait.ImageUrl, user.Phone, user.IdNumber, school.Province); err != nil {
		session.Rollback()
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err.Error()})
		return
	}
	// 备案教练
	if err = coach.RecordCoach(school.InstitutionCode, user, school.Province, school.City, portrait.InstitutionCode, "", portrait.ImageUrl); err != nil {
		session.Rollback()
		c.JSON(http.StatusOK, gin.H{"code": 0, "msg": err.Error()})
		return
	}

	// 设置教练记录状态为1（正常状态）
	coach.RecordStatus = "1"
	coach.RecordStatus2 = "0"
	coach.ApprovalStatus = "0"

	// 更新教练记录状态
	_, err = session.Exec("update dts_coach set record_status=?,record_status2=?,approval_status=?  where id = ?", "1", "0", "0", coach.Id)
	if err != nil {
		session.Rollback()
		c.JSON(http.StatusOK, gin.H{"code": 0, "msg": err.Error()})
		return
	}

	// 提交事务
	err = session.Commit()
	if err != nil {
		session.Rollback()
		c.JSON(http.StatusOK, gin.H{"code": 0, "msg": err.Error()})
		return
	}

	// 如果成功编辑教练员，返回成功信息
	c.JSON(http.StatusOK, gin.H{"code": 200, "msg": "编辑教练员成功"})
	return

}

func DeleteCoach(c *gin.Context) {
	var (
		coachId  string
		schoolId string
		coach    *models.Coach
		url      string
		err      error
		retMap   map[string]interface{}
		reqType  int64
	)
	// 获取请求中的教练ID参数
	if coachId = c.Query("coach_id"); coachId == "" {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "缺少教练信息"})
		return
	}

	// 获取请求中的驾校ID参数
	if schoolId = c.Query("school_id"); schoolId == "" {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "缺少驾校ID"})
		return
	}

	// 查询指定驾校ID的驾校信息
	ok, school, err := new(models.School).GetSchoolById(cast.ToInt(schoolId))
	if err != nil || !ok {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "查询驾校信息失败"})
		return
	}

	// 获取数据库引擎实例
	var engine = models.Engine

	// 创建一个新的数据库会话
	var session = engine.NewSession()

	// 确保在函数结束时关闭会话
	defer session.Close()

	// 开始一个数据库事务
	if err := session.Begin(); err != nil {
		// 如果事务开始失败，返回错误信息
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "事务开始失败", "data": err.Error()})
		return
	}

	// 创建一个新的Coach模型实例
	coach = new(models.Coach)

	// 通过ID查询教练信息
	if ok, err := session.ID(coachId).And("school_id = ?", schoolId).Get(coach); err != nil || !ok {
		session.Rollback()
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "查询教练信息失败"})
		return
	}

	// NOTE: 武汉市 接口方法为 GET
	apiMethod := "DELETE"
	isWuHan := school.City == "420100"
	shanDong := school.Province == "370000"
	isAnHui := school.Province == "340000"
	if isWuHan || shanDong || isAnHui {
		apiMethod = "GET"
	}
	if coach.LoginStatus == "1" {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "教练员已登录，不能删除"})
		return
	}
	reqType = 2
	if coach.RecordStatus == "0" {
		coach.Isused = "0"
		coach.Remark = coach.InstitutionCode
		coach.InstitutionCode = ""
		coach.Status = "0"

		// 根据场地ID更新场地信息，如果更新失败，回滚事务并返回错误信息
		if _, err := session.ID(coach.Id).Cols("isused", "remark", "institution_code", "status").Update(coach); err != nil {
			session.Rollback()
			c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "删除教练失败", "data": err.Error()})
			return
		}
		var user models.User
		user.Isused = "0"
		user.Remark = user.Phone
		user.Phone = cast.ToString(time.Now().Unix())
		user.ReidNumber = user.IdNumber
		user.IdNumber = ""
		if _, err := session.ID(coach.UserId).Cols("isused", "remark", "phone", "reid_number", "id_number").Update(user); err != nil {
			session.Rollback()
			c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "删除教练失败", "data": err.Error()})
			return
		}

	} else {
		// 请求获取加密地址
		if coach.Isused == "1" {
			if url, err = GetSignURL("coach-"+coach.InstitutionCode, nil, reqType, school.Province, school.City); err != nil {
				c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "删除教练失败", "data": err.Error()})
				return
			}
			// 请求运管
			var api_log models.ApiLog
			api_log.Url = url
			api_log.Param = ""
			api_log.Method = "POST"
			api_log.UserId, _ = strconv.Atoi(c.PostForm("user_id"))
			api_log.Time = time.Now()
			if retMap, err = APIReq(url, nil, apiMethod); err != nil {
				result, _ := json.Marshal(retMap)
				api_log.Result = string(result)
				api_log.Add()
				c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "删除教练失败", "data": err.Error()})
				return
			}
			result, _ := json.Marshal(retMap)
			api_log.Result = string(result)
			api_log.Add()
			// 获取返回结果中的错误码
			errorcode, _ := cast.ToIntE(retMap["errorcode"])

			if errorcode != 0 {
				// 如果错误码不为0且消息中不包含“不存在”，则返回删除失败信息
				if strings.Contains(cast.ToString(retMap["message"]), "不存在") || strings.Contains(cast.ToString(retMap["message"]), "未备案") {

				} else {
					c.JSON(http.StatusOK, gin.H{"code": 201, "msg": cast.ToString(retMap["message"]) + "1"})
					return
				}
			}
			//设为已删除及离职状态
			coach.Isused = "0"
			coach.Remark = coach.InstitutionCode
			coach.InstitutionCode = ""
			coach.Status = "0"

			// 根据场地ID更新场地信息，如果更新失败，回滚事务并返回错误信息
			if _, err := session.ID(coach.Id).Cols("isused", "remark", "institution_code", "status").Update(coach); err != nil {
				session.Rollback()
				c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "删除教练失败", "data": err.Error()})
				return
			}
			var user models.User
			if _, err := session.ID(coach.UserId).Get(&user); err != nil {
				c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "删除教练失败", "data": err.Error()})
				return
			}
			user.Isused = "0"
			user.Remark = user.Phone
			user.Phone = cast.ToString(time.Now().Unix())
			user.ReidNumber = user.IdNumber
			user.IdNumber = ""
			if _, err := session.ID(coach.UserId).Cols("isused", "remark", "phone", "reid_number", "id_number").Update(user); err != nil {
				log.Println(err)
				session.Rollback()
				c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "删除教练失败", "data": err.Error()})
				return
			}

		}
	}
	session.Commit()
	c.JSON(http.StatusOK, gin.H{"code": 200, "msg": "删除教练成功"})
	return
}
